package com.zyb.eduorder.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zyb.commonutils.JwtUtils;
import com.zyb.commonutils.R;
import com.zyb.eduorder.entity.Order;
import com.zyb.eduorder.entity.vo.OrderQuery;
import com.zyb.eduorder.service.OrderService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author testJava
 * @since 2022-04-13
 */
@RestController
//@CrossOrigin
@RequestMapping("/eduorder/order")
public class OrderController {

    @Resource
    private OrderService orderService;

    //1 生成订单的方法
    @PostMapping("createOrder/{courseId}")
    public R createOrder(@PathVariable("courseId") String courseId, HttpServletRequest request) {
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(userId)) {
            return R.error().code(28004).message("请登录");
        }
        String orderId = orderService.createOrders(courseId, userId);
        return R.ok().data("orderId", orderId);
    }

    //2 根据订单id查询订单的方法
    @GetMapping("getOrderInfo/{orderId}")
    public R getOrderInfo(@PathVariable String orderId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderId);
        Order orderInfo = orderService.getOne(wrapper);
        return R.ok().data("orderInfo", orderInfo);
    }

    //课程ID和用户ID查询课程是否购买
    @GetMapping("isBuyCourse/{courseId}/{userId}")
    public boolean isBuyCourse(@PathVariable String courseId, @PathVariable String userId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        wrapper.eq("member_id", userId);
        wrapper.eq("status", 1);//支付状态 1代表已经支付

        int count = orderService.count(wrapper);
        if (count > 0) { //已经支付
            return true;
        } else {
            return false;
        }
    }

    //条件查询带分页订单列表
    @PostMapping("getOrderPageCondition/{page}/{limit}")
    public R getOrderPageCondition(@PathVariable Long page, @PathVariable Long limit,
                                   @RequestBody OrderQuery orderQuery) {
        IPage<Order> orderPage = orderService.getOrderPage(page, limit, orderQuery);
        List<Order> records = orderPage.getRecords();
        long total = orderPage.getTotal();
        return R.ok().data("rows", records).data("total", total);
    }

    //删除一个订单
    @DeleteMapping("deleteOrder/{id}")
    public R deleteOrder(@PathVariable String id) {
        boolean flag = orderService.removeById(id);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }
}

